-----------------------------------------------------------
--- /shared/xml/xml.lua                                 ---
--- Part of openFrame project                           ---
--- Written by 50p. Additional changes by Orange.       ---
--- Lately edited in revision number 13 by Orange       ---
--- Licensed under BSD licence                          ---
-----------------------------------------------------------

-- Class: XML Class
-- Class which easily allows you to read and write XML files. Extended by <XMLNode Class>.
XML = of.class:new()

--	Function: XML:Load
--	Loads a XML file
--	
--	Required Arguments:
--	   filename - The name of XML file to load
--	   
--	Returns:
--		The result is a XML file object
function XML:Load( filename )
	local xml = {
		rootname,
		filename = filename,
		nodes = { }
	};
	
	local xmlroot = xmlLoadFile( filename );
	if ( not xmlroot ) then return false end
	
	xml.rootname = xmlNodeGetName( xmlroot );
	
	local ParseNodes = function( nodesTable )
		if ( nodesTable and type( nodesTable ) == "table" ) and #nodesTable > 0 then
			local nodes = { };
			for i = 1, #nodesTable do
				table.insert( nodes, XMLNode:new( nodesTable[ i ] ) );
			end
			return nodes;
		end
		return nil;
	end	

	local children = xmlNodeGetChildren( xmlroot );
	if children then
		xml.nodes = ParseNodes( children );
	end
	
	xmlUnloadFile( xmlroot );
	
	local addNode;
	addNode = function( node, parent )
		local tempnode = xmlCreateChild( parent, node.Name );
		for name, value in pairs( node.Attributes ) do
			xmlNodeSetAttribute( tempnode, name, value );
		end
		if node.Value and type( node.Value ) == "string" and #node.Value > 0 then
			xmlNodeSetValue( tempnode, node.Value );
		end
		if node.nodes ~= nil then
			for i = 1, #node.nodes do
				addNode( node.nodes[ i ], tempnode );
			end
		end
	end

	
	
	local save = function( filename )
		filename = ( type( filename ) == "string" ) and filename or xml.filename;
		local file = xmlCreateFile( filename, xml.rootname );
		if file then
			for i = 1, #xml.nodes do
				addNode( xml.nodes[ i ], file );
			end
			return xmlSaveFile( file );
		end
		return false;
	end
	
	return {
		Rootname = xml.rootname,
		Filename = xml.filename,
		Nodes = xml.nodes,
		Save = save,
	}
end

--	Function: XML:Save
--  (start code)
--  	function XML:Save( filename )
--  (end)
--	Saves a XML file
--	
--	Optional Arguments:
--	   filename - The name of XML file to load
--	   
--	Returns:
--		Returns true if successfully saved, false if not.


--	Array: XML.Nodes
--	Array with all XML nodes of a file

--	Array: XML.Rootname
--	The name of root node

--	Array: XML.Filename
--	Name of opened file

function wrongClassUsageMessage( object, method )
	outputDebugString( "calling method incorrectly ( "..object.."Obj."..method.."() )! use "..object.."Obj:"..method.."()", 1 );
end
